#pragma once 

/* 这个是对阿里云短信验证SDK的二次封装 */

#include <cstdlib>
#include <iostream>
#include <memory>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/CommonRequest.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/CommonResponse.h>
#include "logger.hpp"

namespace ChatSystem
{

class DMSClient
{
public:
    using ptr = std::shared_ptr<ChatSystem::DMSClient>;
    DMSClient(const std::string& access_key,
        const std::string& access_key_secret)
        {
            AlibabaCloud::InitializeSdk();
            AlibabaCloud::ClientConfiguration configuration( "cn-qingdao" );
            // 创建客户端时指定超时。
            configuration.setConnectTimeout(1500);
            configuration.setReadTimeout(4000);
            //请确保设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和ALIBABA_CLOUD_ACCESS_KEY_SECRET 。
            AlibabaCloud::Credentials credential(access_key, access_key_secret);
            _client = std::make_unique<AlibabaCloud::CommonClient>(credential, configuration);
        }

    ~DMSClient()
    {
        //释放DMS客户端
        AlibabaCloud::ShutdownSdk();
    }

    //发送验证码
    bool send(const std::string& phone, const std::string& code)
    {
        AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern);
        request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setQueryParameter("Action", "SendSms");
        request.setQueryParameter("PhoneNumbers", "");
        request.setQueryParameter("SignName", "");
        std::string param_code = "{\"code\":\"" + code + "\"}";
        request.setQueryParameter("TemplateCode", param_code);

        auto response = _client->commonResponse(request);
        if (!response.isSuccess()) 
        {
            LOG_ERROR("短信验证码请求失败： {}", response.error().errorMessage().c_str());
            return false;
        }
        return true;
    }
private:
    /* AlibabaCloud::CommonClient不存在默认的构造函数需要在初始化列表中初始化，但是我们这里需要在构造函数的函数体中定义一些变量后才可以
    初始化 AlibabaCloud::CommonClient 对象，为了解决 AlibabaCloud::CommonClient 不存在默认的构造函数需要在初始化列表中初始化的问题，我们
    可以使用智能指针管理这个对象，这样就在构造函数函数体中做完相关操作后再初始化； 或者就是将构造AlibabaCloud::CommonClient对象需要的参数以
    构造函数参数的形式传进来，直接在初始化列表中初始化；
    */
    std::unique_ptr<AlibabaCloud::CommonClient> _client;     
};

}
